<template>
  <!--发票 支付凭证 图片上传/excel文件上传 -->
  <el-upload ref="uploadRef" class="upload-demo" :drag="drag" action="#" :on-change="loadJsonFromFile"
    :on-exceed="handleExceed" :limit="limit" :auto-upload="false">
    <template v-if="drag">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>

      <div v-if="type == 'excel_box' || type == 'excel_yard'" class="el-upload__text">
        拖拽到此 或 <em>点击上传</em>
      </div>
      <div v-if="type == 'img'" class="el-upload__text">
        文件格式：pdf/png/jpg。 图片大小：小于3MB。
      </div>
      <div v-if="type == 'file'" class="el-upload__text">
        文件格式：pdf/png/jpg。 图片大小：小于3MB。
      </div>
      <div v-if="type == 'zip_rar_jpg_png'" class="el-upload__text">
        文件格式：zip/rar/jpg/png 文件。 单文件大小在10MB以内。
      </div>
    </template>
    <el-button v-else type="primary">{{ title }}</el-button>
  </el-upload>
  <div v-if="type == 'excel_box' || type == 'excel_yard'" class="el-upload__text">
    请上传xls/xlsx文件，大小在10MB以内。
  </div>

</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import { getCurrentInstance, onActivated, onMounted, reactive, ref } from 'vue'
import { compressImage } from '@/utils/compress.js'
import { ElMessage, UploadProps, UploadRawFile, genFileId } from 'element-plus'
import { uploadFile } from '@/api/system/upload'
import { invoiceOcr } from '@/api/invoice'
import { uploadBox } from '@/api/boxManage/index'
import { uploadYard, getYardInfo } from '@/api/boxManage/yard'
//ocrIDCard 
import { ocrIDCard, ocrLicense } from '@/api/company/index'

const emit = defineEmits(['ocrIDCard', 'getImgList', 'uploadSuccess','idCardData','idCardDataLinkZM','idCardDataLinkFM','idCardDataGL','idCardDataLink','idCardDataGLLinkZM','idCardDataGLLinkFM'])


const props = defineProps({
  // 父组件向子组件传值
  type: {// img/file/excel_box/excel_yard/zip_rar_jpg_png
    type: String,
    default: 'img'
  },
  needOcr: {
    type: Boolean,
    default: false
  },
  drag: { // 是否拖拽上传
    type: Boolean,
    default: true
  },
  limit: { // 限制上传数量 （达上限后，替换已上传文件）
    type: Number,
    default: 1
  },
  limitForce: { // 强制上传数量 （达上限后，不替换已上传文件，给出提示。注： limitForce 小于 limit 才生效）
    type: Number,
    default: 1
  },
  isFronface: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: '上传文件'
  },
  idCardType:{
    type: String,
    default: 'front'
  },
  idIDCard:{
    type: Boolean,
    default: false
  }
})

onActivated(() => {
  console.log('onActivated')
  if (props.type == 'excel_box') {
    clearFiles()
  }
})

//分类校验
const beforeAvatarUpload = (rawFile: any) => {
  if (props.type == 'zip_rar_jpg_png') {
    let list = ['image/jpeg', 'image/jpg', 'image/png', 'application/x-zip-compressed']
    const isAccess = list.includes(rawFile.raw.type);
    const isLt10M = rawFile.size / 1024 / 1024 < 10;
    const isLimit = uploadFiles.value.length <= props.limitForce
    if (!isAccess) {
      ElMessage.error('上传文件只能是 zip/rar/jpg/png 格式!');
      return false
    }
    if (!isLt10M) {
      ElMessage.error('上传大小不能超过 10MB!');
      return false
    }
    if (!isLimit) {
      ElMessage.error('上传一次不能超过 ' + props.limitForce + ' 个!');
      return false
    }

  } else {
    let list = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf']
    const isAccess = list.includes(rawFile.raw.type);
    const isLt3M = rawFile.size / 1024 / 1024 < 3;
    if (!isAccess) {
      ElMessage.error('上传文件只能是 pdf/png/jpg 格式!');
      return false
    }
    if (!isLt3M) {
      ElMessage.error('上传大小不能超过 3MB!');
      return false
    }
  }
  return true
}

//上传
const loadJsonFromFile = async (file: any, fileList: never[]) => {
  uploadFiles.value = fileList //文件
  let imgList: any = []
  if (props.type == 'excel_box' || props.type == 'excel_yard') {
    imgList = await submitUploadExcel()
  } else {
    const result = beforeAvatarUpload(file)
    if (!result) {
      fileList.splice(-1, 1);
    }
    uploadFiles.value = fileList  // 上传成功的 图片list
    imgList = await submitUpload()
  }
  
  if(props.idIDCard){
    if(props.isFronface){
        localStorage.setItem('isFile', imgList[0].url)
    }else{
        localStorage.setItem('theFile', imgList[0].url)
    }
    if(localStorage.getItem('isFile') && localStorage.getItem('theFile')){
          const idData = {
            isFile: localStorage.getItem('isFile'),
            theFile: localStorage.getItem('theFile')
          }
          ocrIDCard(JSON.stringify(idData)).then(res => {
            console.log(res,'resssssssss')
            ElMessage.success('身份证核验成功')
            localStorage.removeItem('isFile');
            localStorage.removeItem('theFile');
            // getIDCardData(res)
            emit('idCardData', res);
            emit('idCardDataGL', res);
          }).catch(err => {
            console.log(err,'errssssssss')

            ElMessage.error('身份证核验失败，请重新上传')
            localStorage.removeItem('isFile');
            localStorage.removeItem('theFile');
          })
    }
  }
  
  //支持ocr
  if (props.needOcr) {
    if (imgList.length == 0 || !imgList[0].url) return
    const url = imgList[0].url  // "http://47.122.3.254:9000/default/20241023/5cd11184e62b4ad09b7a1c2d6162051f.pdf"
    const invoice = await getIDCardOcr(url)
    emit('ocrIDCard', invoice) // 结果出口
  } else {
    emit('getImgList', imgList) // 结果出口
  }
  // submitUpload()
}

// 上传img 
// * submitUpload()方法存在外部调用，不可随意更改
let resultList = ref([])
const uploadFiles = ref([])
const submitUpload = async () => {
  resultList.value = []
  let fileList = uploadFiles.value
  for (let i = 0; i < fileList.length; i++) {
    let file = fileList[i]
    let formData = new FormData()
    if (file.raw) {
      formData.append('file', file.raw)
      await uploadFile(formData).then((res: any) => {
        resultList.value.push(res.data)
        console.log(props.idIDCard,props.isFronface,props.idCardType)
         if(props.idIDCard){
          if(props.isFronface){
            if(props.idCardType == '1'){
              emit('idCardDataLinkZM', res.data);
            }else if(props.idCardType == '2'){
              emit('idCardDataGLLinkZM', res.data);
            }     
          }else{
            if(props.idCardType == '1'){
              emit('idCardDataLinkFM', res.data);
            }else if(props.idCardType == '2'){
              emit('idCardDataGLLinkFM', res.data);
            }
          }
        }
        
        
      })
    }
  }
  uploadFiles.value = []
  return resultList.value
}

//上传excel
const submitUploadExcel = async () => {
  resultList.value = []
  let fileList = uploadFiles.value
  for (let i = 0; i < fileList.length; i++) {
    if (i == fileList.length - 1) { //只执行最后一个文件
      let file = fileList[i]
      let formData = new FormData()
      if (file.raw) {
        formData.append('file', file.raw)
        if (props.type == 'excel_box') {
          await uploadBox(formData).then((res: any) => {
            resultList.value.push(res.data)
            emit('uploadSuccess')
          })
        } else {
          await uploadYard(formData).then((res: any) => {
            resultList.value.push(res.data)
            emit('uploadSuccess')
          })
        }
      }
    }
  }
  uploadFiles.value = []
  return resultList.value
}


const getIDCardOcr = async (fileUrl: string) => {
  const data = {}
  data[props.isFronface ? 'isFile' : 'theFile'] = fileUrl
  return await ocrIDCard(data)
}

//清空已上传文件
const { proxy } = getCurrentInstance();
const clearFiles = () => {
  proxy.$refs.uploadRef.clearFiles();
}
//自动替换上一个文件
const handleExceed: UploadProps['onExceed'] = (files) => {
  clearFiles()
  const file = files[0] // 获取上传文件首个
  file.uid = genFileId()
  proxy.$refs.uploadRef.handleStart(file)
}

defineExpose({
  resultList,
  // submitUpload,
  // urlListShow,
  uploadFiles,
  getIDCardOcr,
  clearFiles
})

</script>
<style scoped>
.upload-demo {}
</style>
